<template>
    <div>
        <ModalComponent @open="handleOpen" modal-name="test-questions-info" :title="(type == 'add' ? '创建' : '编辑') + '试题'"
            :close-on-click-modal="false" size="1024px">
            <div>
                <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" size="large">
                    <el-form-item label="题干" prop="stem">
                        <div style="border: 1px solid #ccc;width: 960px">
                            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                                :defaultConfig="toolbarConfig" :mode="mode" />
                            <Editor style="height: 320px; overflow-y: hidden;" v-model="form.stem"
                                :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                        </div>
                        <!-- <el-input v-model="form.stem" type="textarea" placeholder="请输入题干内容" /> -->
                    </el-form-item>
                    <!-- <el-form-item label="图片" prop="imgUrl">
                        <UploadImage v-model="form.imgUrl" />
                    </el-form-item> -->
                    <el-form-item label="题型">
                        <el-radio-group v-model="form.subjectType" @change="handleSubjectTypeChange"
                            :disabled="type == 'edit'">
                            <el-radio :label="1">单选题</el-radio>
                            <el-radio :label="2">主观题</el-radio>
                            <el-radio :label="3">多选题</el-radio>
                            <el-radio :label="4">判断题</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <!-- 选择题使用 -->
                    <el-form-item label="选项" v-if="form.subjectType != 2">
                        <div class="options-container">
                            <div v-for="item, index in options">
                                <span class="sort">
                                    {{ option_title[index] }}
                                </span>
                                <div class="center">
                                    <el-input v-model="item.content" placeholder="填写选项" size="large"
                                        :disabled="form.subjectType == 4">
                                    </el-input>
                                </div>
                                <div class="right" v-if="form.subjectType != 4">
                                    <UploadImage v-model="item.content" :mini="true" />
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="正确选项" v-if="form.subjectType != 2" prop="correctCase">
                        <el-checkbox-group v-model="form.correctCase" v-if="form.subjectType == 3">
                            <el-checkbox v-for="title in (option_title)" :key="title" :label="title">{{
                                title
                            }}</el-checkbox>
                        </el-checkbox-group>
                        <el-radio-group v-model="form.correctCase" v-else>
                            <el-radio :label="title"
                                v-for="title in (form.subjectType == 4 ? option_title.slice(0, 2) : option_title)"
                                :key="title"> {{ title }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="分数" prop="score">
                        <el-input v-model="form.score" type="number" placeholder="请输入分数" />
                    </el-form-item>
                    <el-form-item label="">
                        <el-button type="primary" @click="handleSave">保存</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </ModalComponent>
    </div>
</template>
<script setup >
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import ModalComponent from "@/components/modal/index.vue"
import UploadImage from "@/components/upload-image/index.vue"
import { SubjectAdd, SubjectUpdate } from "@/api/gradingTeacher.js"
import { ElMessage } from 'element-plus';
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
const editorRef = shallowRef()
const toolbarConfig = {
    toolbarKeys: [
        'headerSelect',
        'bold',
        'color',
        "bgColor",
        // 'code',
        "uploadImage",
        "todo",
        "redo",
        "undo"
    ],
}
const Authorization = localStorage.getItem('token') ? localStorage.getItem('token') : "";

const editorConfig = {
    placeholder: '',
    MENU_CONF: {
        "uploadImage": {
            server: '/api/uploadFile',
            fieldName: 'multipartFile',
            maxFileSize: 10 * 1024 * 1024, // 10M
            headers:{
                Authorization
            },
            customInsert(res, insertFn) {
                let url = '';
                let alt = '';
                let href = '';
                if(res.success){
                    url = res.entity.fileUrl
                }
                insertFn(url, alt, href)
            },

        }
    }
}
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
const emit = defineEmits(['update'])
const option_title = ref(["A", "B", "C", "D"]);
const form = ref({});
const options = ref([]);
const type = ref('add')
const eventId = ref("")
const ruleFormRef = ref()
const validateScore = (rule, value, callback) => {
    if (value <= 0) {
        callback(new Error('请输入正确的分数'))
    } else {
        callback();
    }
}
const validateCorrectCase = (rule, value, callback) => {
    if (form.value.subjectType == 2) {
        callback();
    }
    if (value === '') {
        callback(new Error('请输入正确选项'))
    } else {
        if (value <= 0) {
            callback(new Error('请输入正确选项'))
        }
        callback();
    }
}
const rules = ref({
    stem: [
        { required: true, message: '请输入题干', },
    ],
    score: [
        { required: true, message: '请输入分数', },
        { validator: validateScore, },
    ],
    correctCase: [
        { validator: validateCorrectCase, },
    ]
});
const handleOpen = (e) => {
    type.value = e.type;
    eventId.value = e.eventId;
    if (e.type == 'add') {
        form.value = {
            subjectType: 1,
            score: 1,
            imgUrl: ""
        }
        handleSubjectTypeChange(1)
    } else if (e.type == 'edit') {
        e.data.score = Number(e.data.score)
        form.value = e.data;
        if (e.data.subjectType == 4) {
            options.value = [
                {
                    content: e.data.caseA,
                }, {
                    content: e.data.caseB,
                },
            ];
        } else {
            options.value = [
                {
                    content: e.data.caseA,
                }, {
                    content: e.data.caseB,
                },
                {
                    content: e.data.caseC,
                }, {
                    content: e.data.caseD,
                }
            ];
        }
        if (e.data.subjectType == 3) {
            form.value.correctCase = e.data.correctCase.split(',')
        }
    }
}
const handleSubjectTypeChange = (type) => {
    if (type == 3) {
        form.value.correctCase = [];
    } else {
        form.value.correctCase = "";
    }
    if (type == 4) {
        options.value = [
            {
                content: "对",
            }, {
                content: "错",
            },
        ];
        option_title.value = ["A", "B"];
    } else {
        options.value = [
            {
                content: "",
            }, {
                content: "",
            },
            {
                content: "",
            }, {
                content: "",
            }
        ];
        option_title.value = ["A", "B", "C", "D"];
    }

}

const handleSave = () => {
    ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            let data = JSON.parse(JSON.stringify(form.value));
            let json = [data];
            if (data.correctCase instanceof Array) {
                data.correctCase = data.correctCase.join(',')
            }
            if (data.subjectType == 4) {
                data.caseA = options.value[0].content;
                data.caseB = options.value[1].content;
                data.caseC = ""
                data.caseD = "";
            } else {
                data.caseA = options.value[0].content;
                data.caseB = options.value[1].content;
                data.caseC = options.value[2].content;
                data.caseD = options.value[3].content;
            }
            let res;
            if (type.value == 'edit') {
                res = await SubjectUpdate(data)
            } else {
                res = await SubjectAdd(json, {
                    eventId: eventId.value,
                })
            }
            if (!res.success) {
                ElMessage.error(res.message);
            } else {
                ElMessage.success(res.message);
                emit('update')
            }
        } else {
            return false;
        }

    })

}
onMounted(() => {
    console.log('mounted!')
})
</script>
<style lang="scss" scoped>
.options-container {
    width: 100%;

    >div {
        padding-bottom: 16px;
        display: flex;
        align-items: flex-start;
        width: 100%;

        .sort {
            width: 32px;
            height: 40px;
            display: flex;
            justify-content: center;
            background-color: #ccc;
            border-radius: 4px;
        }

        .center {
            padding: 0 8px;
            flex-shrink: 0;
            box-sizing: border-box;
            width: 420px;
        }

        .right {
            flex-shrink: 0;
        }
    }
}
</style>